package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.zhangshizhi.wx.collect.CollectBO;
import com.cskaoyan.bean.zhangshizhi.wx.collect.CollectVO;
import com.cskaoyan.bean.zhangshizhi.wx.collect.GoodsCollected;
import com.cskaoyan.mapper.MarketCollectMapper;
import com.cskaoyan.service.CollectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author little ants
 * @since 2022/06/29 15:38
 */

@Service
public class CollectServiceImpl implements CollectService {
    @Autowired
    MarketCollectMapper mapper;

    @Override
    public CollectVO selectCollect(CollectBO collectBO) {
        PageHelper.startPage(collectBO.getPage(),collectBO.getLimit());

        List<GoodsCollected> goodsList = mapper.selectByValueId(collectBO.getUserId());

        PageInfo<GoodsCollected> pageInfo = new PageInfo<>(goodsList);

        CollectVO collectVO = new CollectVO();
        collectVO.setList(goodsList);
        collectVO.setPage(collectBO.getPage());
        collectVO.setPages(pageInfo.getPages());
        collectVO.setLimit(collectBO.getLimit());
        collectVO.setTotal((int) pageInfo.getTotal());


        return collectVO;
    }

    @Override
    public void addGoodsToCollect(MarketCollect marketCollect) {
        // 先查询收藏中是否有，有就改变状态，没有就添加
        MarketCollectExample marketCollectExample = new MarketCollectExample();
        MarketCollectExample.Criteria criteria = marketCollectExample.createCriteria();
        criteria.andUserIdEqualTo(marketCollect.getUserId());
        criteria.andValueIdEqualTo(marketCollect.getValueId());
        List<MarketCollect> marketCollects = mapper.selectByExample(marketCollectExample);
        Date date = new Date();
        // size为0,说明没有收藏过,直接添加
        if (marketCollects.size() == 0){
            marketCollect.setAddTime(date);
            marketCollect.setUpdateTime(date);
            mapper.insertSelective(marketCollect);
            return;
        }
        // 同一商品在同一用户的收藏夹里只会出现一次
        if (marketCollects.get(0).getDeleted() == false){
            // 该商品被收藏过，并且被取消收藏，更改状态即可
            marketCollect.setDeleted(true);
            marketCollect.setUpdateTime(date);
            mapper.updateByExampleSelective(marketCollect,marketCollectExample);
            return;
        }
        // 该商品已经在该用户的收藏夹，取消收藏，更改状态即可
        marketCollect.setDeleted(false);
        marketCollect.setUpdateTime(date);
        mapper.updateByExampleSelective(marketCollect,marketCollectExample);

    }
}
